package com.futu.intelligence.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class DeepSeekUtil {

    @Value("${deepseek.api-key:}")
    private String apiKey;

    @Value("${deepseek.api-url}")
    private String apiUrl;

    /**
     * 生成旅游计划
     * @param city 城市
     * @param days 天数
     * @return 旅游计划JSON字符串
     */
    public String generateTravelPlan(String city, int days) {
        if (apiKey == null || apiKey.trim().isEmpty() || apiKey.equals("sk-3c7de52507f14c0694eb21a01c594f9e")) {
            System.out.println("【模拟模式】生成旅游计划：city=" + city + ", days=" + days);
            return generateMockTravelPlan(city, days);
        }

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(apiUrl);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + apiKey);

            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", "deepseek-chat"); // DeepSeek模型名称

            JSONArray messages = new JSONArray();

            // 系统消息
            JSONObject systemMessage = new JSONObject();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是一个旅游规划专家，根据用户指定的城市和天数，规划合理的旅游路线，每天游览2-4个景点。");
            messages.put(systemMessage);

            // 用户消息
            JSONObject userMessage = new JSONObject();
            userMessage.put("role", "user");
            userMessage.put("content", String.format(
                "请为我规划一个%s天的%s旅游行程。请按照以下JSON格式返回，不要有其他文字：\n" +
                "{\n" +
                "  \"city\": \"%s\",\n" +
                "  \"days\": %d,\n" +
                "  \"plan\": [\n" +
                "    {\n" +
                "      \"day\": 1,\n" +
                "      \"attractions\": [\n" +
                "        {\"name\": \"景点1名称\", \"description\": \"简短描述\"},\n" +
                "        {\"name\": \"景点2名称\", \"description\": \"简短描述\"}\n" +
                "      ]\n" +
                "    },\n" +
                "    // 更多天数...\n" +
                "  ]\n" +
                "}", days, city, city, days));
            messages.put(userMessage);

            requestBody.put("messages", messages);
            requestBody.put("temperature", 0.7);
            requestBody.put("max_tokens", 2000);

            // 设置请求体
            StringEntity stringEntity = new StringEntity(requestBody.toString(), ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);

            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity);
                    JSONObject jsonResponse = new JSONObject(result);

                    // 提取生成的内容
                    if (jsonResponse.has("choices") && jsonResponse.getJSONArray("choices").length() > 0) {
                        JSONObject choice = jsonResponse.getJSONArray("choices").getJSONObject(0);
                        if (choice.has("message") && choice.getJSONObject("message").has("content")) {
                            return choice.getJSONObject("message").getString("content");
                        }
                    }
                }
            }

            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return generateMockTravelPlan(city, days);
        }
    }

    /**
     * 生成模拟旅游计划数据
     */
    private String generateMockTravelPlan(String city, int days) {
        System.out.println("【模拟数据】city=" + city + ", days=" + days);
        JSONObject result = new JSONObject();
        result.put("city", city);
        result.put("days", days);

        JSONArray plan = new JSONArray();

        // 根据城市生成不同的景点
        String[][] attractions = getAttractionsByCity(city, days);

        for (int day = 1; day <= days; day++) {
            JSONObject dayPlan = new JSONObject();
            dayPlan.put("day", day);

            JSONArray dayAttractions = new JSONArray();
            String[] dayAttractionList = attractions[day - 1];

            for (String attraction : dayAttractionList) {
                JSONObject attractionObj = new JSONObject();
                attractionObj.put("name", attraction);
                attractionObj.put("description", getAttractionDescription(attraction));
                dayAttractions.put(attractionObj);
            }

            dayPlan.put("attractions", dayAttractions);
            plan.put(dayPlan);
        }

        result.put("plan", plan);
        System.out.println("【模拟数据结果】" + result.toString());
        return result.toString();
    }

    /**
     * 根据城市获取景点列表
     */
    private String[][] getAttractionsByCity(String city, int days) {
        String[][] base;
        if (city.contains("北京")) {
            base = new String[][]{
                {"天安门广场", "故宫博物院", "景山公园"},
                {"颐和园", "圆明园", "清华大学"},
                {"八达岭长城", "明十三陵", "鸟巢"}
            };
        } else if (city.contains("上海")) {
            base = new String[][]{
                {"外滩", "南京路步行街", "豫园"},
                {"东方明珠", "上海科技馆", "陆家嘴"},
                {"迪士尼乐园", "田子坊", "新天地"}
            };
        } else if (city.contains("广州")) {
            base = new String[][]{
                {"广州塔", "珠江夜游", "上下九步行街"},
                {"长隆野生动物园", "陈家祠", "沙面岛"},
                {"白云山", "越秀公园", "北京路步行街"}
            };
        } else {
            base = new String[][]{
                {"城市公园", "博物馆", "商业街"},
                {"历史古迹", "文化广场", "购物中心"},
                {"自然景观", "主题公园", "美食街"}
            };
        }
        // 保证天数不超过base长度，超出则循环使用
        String[][] result = new String[days][];
        for (int i = 0; i < days; i++) {
            result[i] = base[i % base.length];
        }
        return result;
    }

    /**
     * 获取景点描述
     */
    private String getAttractionDescription(String attraction) {
        switch (attraction) {
            case "天安门广场": return "世界上最大的城市广场，是北京的地标性建筑";
            case "故宫博物院": return "明清两代的皇家宫殿，世界文化遗产";
            case "颐和园": return "中国现存最大、保存最完整的皇家园林";
            case "外滩": return "上海最著名的地标，黄浦江畔的万国建筑博览群";
            case "东方明珠": return "上海的标志性建筑，亚洲第三高塔";
            case "广州塔": return "广州的地标建筑，世界第三高塔";
            default: return "著名的旅游景点，值得一游";
        }
    }
}
